import "./picker/picker-extend.css";
import "./assets/styles/global.less";

import $ from "jquery";
import PickerExtend from "./picker/picker-extend";
import { background, agreement, recent } from "./data";
import { getAreaList, getLTPostList, getLocaltion, submit } from "./api";
import { toggleSelectPhone } from "./selectPhone";
import toast from "./toast";

function getChannel() {
  const url = new URL(location.href);
  return url.searchParams.get("channel");
}

/**
 *
 * @param {import("./api").Area} area
 * @param {number} [depth]
 */
function getPickData(area, depth) {
  if (typeof depth == "undefined") depth = -1;
  if (depth != -1) --depth;

  const data = {
    id: area.value,
    value: area.text,
  };
  if (depth != 0 && area.children) {
    data.childs = area.children.map((childArea) => {
      return getPickData(childArea, depth);
    });
  }
  return data;
}

function toggleLoading() {
  const tag = $("#submitLoading");
  tag.toggle();

  if (tag.css("display") == "none") {
    $(document.body).css("overflow", "auto");
  } else {
    $(document.body).css("overflow", "hidden");
  }
}

const keyMap = {
  id: "value",
  value: "text",
  childs: "children",
};

function setupUI() {
  //修改标题
  // $("title").text("大王卡");

  const body = $(document.body);
  agreement
    .trim()
    .split("\n")
    .forEach((line) => {
      $(".ui-dialog>.content").append($(`<p>${line}</p>`));
    });

  $(".ui-mask").on("transitionend", () => {
    if ($(".ui-mask").css("opacity") == "0") {
      $(".ui-mask").hide();
    }
  });

  $("#acceptBtn").on("click", () => {
    $(".ui-mask").css("opacity", 0);
    $("body").css("overflow", "auto");
  });

  $("#agreement").on("click", () => {
    $("body").css("overflow", "hidden");
    $(".ui-mask").show();
    $(".ui-mask").css("opacity", 1);
  });

  const bkHeaderTag = $("#bk-header");
  bkHeaderTag.addClass("bk-image");
  bkHeaderTag.attr("src", background.head);

  background.content.forEach((bk) => {
    body.append($(`<img class="bk-image" src="${bk}" />`));
  });

  const autoscrollContainer = $(".autoscroll-container");
  let recentListIndex = 0;
  recent.forEach(({ content, time }) => {
    autoscrollContainer.append(
      $(`<div class="inner">
      <div>${content}</div>
      <div>${time}</div>
    </div>`)
    );
  });

  setInterval(() => {
    ++recentListIndex;
    if (recentListIndex >= recent.length) {
      autoscrollContainer.css("transition", "transform 0s");
      recentListIndex = 1;
      const tag = $(
        autoscrollContainer[0].children[autoscrollContainer.children.length - 1]
      );
      tag.remove();
      autoscrollContainer.prepend(tag);
      autoscrollContainer.css("transform", "translateY(0px)");
      setTimeout(() => {
        autoscrollContainer.css("transition", "");
        autoscrollContainer.css(
          "transform",
          `translateY(-${recentListIndex * 18}px)`
        );
      }, 0);
      return;
    }
    autoscrollContainer.css(
      "transform",
      `translateY(-${recentListIndex * 18}px)`
    );
  }, 2 * 1000);
}

async function main() {
  setupUI();

  const channel = getChannel();

  if (!channel || channel.length == 0) {
    toast("访问错误，缺少channel参数，请勿直接访问该页面");
    return;
  }

  /**@type {import("./api").SubmitFormData} */
  const submitFormData = {
    numInfo: {
      city: null,
      prov: null,
      number: "",
      numberKey: "",
    },
    params: { channel },
    postInfo: {
      prov: null,
      city: null,
      district: null,
      address: "",
      receiverMobile: "",
      receiverName: "",
      certName: "",
      certNo: "",
    },
  };

  //获取归属地列表，并处理
  const areaList = await getAreaList();
  const location = await getLocaltion(channel);
  $("#location").text(`${location.provinceName} ${location.cityName}`);
  submitFormData.numInfo.city = {
    code: location.cityCode,
    name: location.cityName,
  };
  submitFormData.numInfo.prov = {
    code: location.provinceCode,
    name: location.provinceName,
  };

  $("#selectPhone").on("click", function () {
    toggleSelectPhone({
      channel,
      phoneProvinceCode: submitFormData.numInfo.prov.code,
      phoneProvinceName: submitFormData.numInfo.prov.name,
      phoneCityCode: submitFormData.numInfo.city.code,
      phoneCityName: submitFormData.numInfo.city.name,
      callback(data) {
        if (data) {
          submitFormData.numInfo.number = data.number;
          submitFormData.numInfo.numberKey = data.uuid;
          $("#phoneNumber").text(data.number);
        }
      },
    });
  });

  new PickerExtend({
    keyMap,
    trigger: "#location",
    title: "请选择归属地地区",
    wheels: [
      {
        data: areaList,
      },
    ],
    position: [0, 0],
    callback: function (_, data) {
      submitFormData.numInfo.prov = {
        code: data[0].value,
        name: data[0].text,
      };
      submitFormData.numInfo.city = {
        code: data[1].value,
        name: data[1].text,
      };
    },
  });

  $("#name").on("change", () => {
    submitFormData.postInfo.receiverName = $("#name").val();
    submitFormData.postInfo.certName = $("#name").val();
  });

  $("#phone").on("change", () => {
    submitFormData.postInfo.receiverMobile = $("#phone").val();
  });

  $("#address").on("change", () => {
    submitFormData.postInfo.address = $("#address").val();
  });

  $("#certNo").on("change", () => {
    submitFormData.postInfo.certNo = $("#certNo").val();
  });

  $("#submitBtn").on("click", async () => {
    if (
      submitFormData.postInfo.certName.length < 2 ||
      submitFormData.postInfo.certName.length > 16
    ) {
      toast("姓名必须在2-16个字符之间");
      return;
    }

    if (
      !/^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/.test(
        submitFormData.postInfo.certNo
      ) &&
      !/^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(
        submitFormData.postInfo.certNo
      )
    ) {
      toast("身份证不合法");
      return;
    }

    if (!/1[0-9]{10}$/.test(submitFormData.postInfo.receiverMobile)) {
      toast("手机号码填写错误");
      return;
    }

    if (!submitFormData.postInfo.prov) {
      toast("所在地区不能为空");
      return;
    }
    if (submitFormData.postInfo.address.trim().length == 0) {
      toast("详细地址不能为空");
      return;
    }
    if (submitFormData.numInfo.number.length == 0) {
      toast("请选择一个手机号码");
      return;
    }

    if (!document.querySelector("#agreementAccept").checked) {
      toast("请阅读并同意《入网许可协议&个人信息收集证明》");
      return;
    }

    if (submitFormData.postInfo.certNo) console.log("提交数据", submitFormData);
    try {
      toggleLoading();
      await submit(submitFormData);
    } catch (error) {
      console.error(error);
    } finally {
      toggleLoading();
    }
  });

  const postList = await getLTPostList();
  const selectAreaPicker = new PickerExtend({
    keyMap,
    trigger: "#selectArea",
    disableTrigger: true,
    title: "请选择区/县",
    wheels: [
      {
        data: postList,
      },
    ],
    position: [0, 0, 0],
    callback: function (_, data) {
      const [prov, city, district] = data;
      if (prov) {
        submitFormData.postInfo.prov = {
          code: prov.value,
          name: prov.text,
        };
      } else {
        submitFormData.postInfo.prov = null;
      }
      if (city) {
        submitFormData.postInfo.city = {
          code: city.value,
          name: city.text,
        };
      } else {
        submitFormData.postInfo.city = null;
      }
      if (district) {
        submitFormData.postInfo.district = {
          code: district.value,
          name: district.text,
        };
      } else {
        submitFormData.postInfo.district = null;
      }
      console.log(submitFormData);
    },
  });

  $("#selectAreaTrigger").on("click", () => {
    selectAreaPicker.show();
  });
}

main();
